package com.vanke.kotlin

import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.squareup.picasso.Picasso
import com.vanke.kotlin.domain.Forecast
import com.vanke.kotlin.domain.ForecastList
import kotlinx.android.synthetic.main.item_forecast.view.*

/**
 * @name Kotlin
 * @package name：com.vanke.kotlin
 * @class describe
 * @anthor shiyuchuan
 * @time 2017/7/20 17:17
 */
class ForecastListAdapter(val weekForecast: ForecastList,
                          val itemClick: (Forecast) -> Unit)
    : RecyclerView.Adapter<ForecastListAdapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {

        val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.item_forecast, parent, false)
        return ViewHolder(view, itemClick)

    }

    override fun getItemCount(): Int = weekForecast.size()

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bindForecast(weekForecast[position])
    }

    class ViewHolder(view: View, val itemClick: (Forecast) ->Unit)
        : RecyclerView.ViewHolder(view) {
        private val iconView: ImageView

        private val dateView: TextView

        private val descriptionView: TextView

        private val maxTemperatureView: TextView

        private val minTemperatureView: TextView

        init {
            iconView = view.icon
            dateView = view.date
            descriptionView = view.description
            maxTemperatureView = view.maxTemperature
            minTemperatureView = view.minTemperature
        }

        fun bindForecast(forecast: Forecast): Unit {
            with(forecast) {
                Picasso.with(itemView.context).load(iconUrl).into(iconView)
                dateView.text = date.toDateString()
                descriptionView.text = description
                maxTemperatureView.text = "$high"
                minTemperatureView.text = "$low"
                itemView.setOnClickListener { itemClick(this) }
            }
        }
    }

    public interface OnItemClickListenner{
        operator  fun invoke(forecast: Forecast)
    }

}
